<template>
  <div style="margin-top: 70px">
    <upload-excel :on-success="handleSuccess" :before-upload="beforeUpload" />
  </div>
</template>

<script>
import { formatExcelDate } from '@/utils'
import { addExcel } from '@/api/employees'
export default {
  name: 'Hr75Import',
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    async doImport(data) {
      try {
        const res = await addExcel(data)
        // console.log(res)
        this.$message.success(res.message)
        // 页面后退
        this.$router.back()
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    handleSuccess({ results, header }) {
      const data = this.transExcel(results)
      this.doImport(data)
      // console.log('这是上传的结果:', results, header)
      // console.log(this.transExcel(results))
    },
    transExcel(result) {
      // 准备一个中英文转换的映射对象
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      // 循环遍历传入的数组
      return result.map(zhObj => {
        // 创建一个空对象 zhObj => {入职日期:2002-6, 手机号: 138..., 姓名:小张,........}
        const enObj = {}
        // 拿到result的中文key => ['入职日期','手机号','姓名', .....]
        const zhKeys = Object.keys(zhObj)
        // 遍历上面拿到的中文keys
        zhKeys.forEach(zhKey => {
          // 得到数组里的每个中文key
          // 利用每个中文key拿到对应的英文值enkey
          const enKey = mapInfo[zhKey]
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            enObj[enKey] = new Date(formatExcelDate(zhObj[zhKey]))
          } else {
            // 然后再空对象enObj里添加英文属性 它对应的值是中文的键值
            enObj[enKey] = zhObj[zhKey]
          }
        })
        // 返回出来的对象就实现了key值的中英文对调
        return enObj
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
